<template>
  <use-page-header/>
  <div class="wrapper">
    <a-card>
      <a-flex justify="space-between" class="margin-bottom-md">
        <router-link to="/admin/coffee/create">
          <a-button type="primary"><plus-outlined/>发布新品</a-button>
        </router-link>
        <filter-coffee @change="onChange"/>
      </a-flex>
     <a-list :data-source="data" :loading="state.loading">
      <template #renderItem="{item}">
        <a-list-item :style="{paddingLeft:0,paddingRight:0}">
          <a-list-item-meta>
            <template #title>
              <router-link :to="{name:'CoffeeDetail',params:{id:item.id}}" 
                target="_blank" class="font-size-lg font-weight-500">
                {{ item.title }}
              </router-link>
            </template>
            <template #avatar>
              <a-badge-ribbon text="推荐" color="red" v-if="item.recommend" placement="start">
                <router-link :to="{name:'CoffeeDetail',params:{id:item.id}}">
                  <a-avatar slot="avatar" shape="square" :size="120" :src="staticURL+item.cover" target="_blank"/>
                </router-link>
              </a-badge-ribbon>
               <router-link :to="{name:'CoffeeDetail',params:{id:item.id}}" v-else>
                  <a-avatar slot="avatar" shape="square" :size="120" :src="staticURL+item.cover" target="_blank"/>
                </router-link>
            </template>
            <template #description>
              <div class="margin-bottom-sm">
                <a-space class="category">
                  <template #split>/</template>
                  <span>分类</span>
                  <span v-for="(category,index) in item.category" :key="index">{{category.name}}</span>
                </a-space>
              </div>
              <a-typography-paragraph class="a-text-secondary margin-bottom-sm" :ellipsis="{ rows: 2}" :content="item.description"/>
              <a-space>
                <a-tooltip title="发布者"><span class="hover"><user-outlined/> {{ item.user_info.username }}</span></a-tooltip>
                <a-divider type="vertical"/>
                <a-tooltip title="浏览数"><span class="hover"><eye-outlined/> {{ item.views }}</span></a-tooltip>
                <a-divider type="vertical"/>
                <a-tooltip title="点赞数"><span class="hover"><heart-outlined/> {{ item.likes }}</span></a-tooltip>
                <a-divider type="vertical"/>
                <a-tooltip title="发布时间"><span class="hover"><clock-circle-outlined/> {{ item.create_time }}</span></a-tooltip>
              </a-space>
            </template>
          </a-list-item-meta>
          <div style="padding-left: 32px;">
            <a-tag color="green" v-if="item.status">正常</a-tag>
            <a-tag color="red" v-else>已关闭</a-tag>
          </div>
          <template #actions>
            <router-link :to="{name:'CoffeeDetail',params:{id:item.id}}" target="_blank">
              <span class="action"><file-search-outlined/> 详情</span>
            </router-link>
            <span class="action" @click="showQrcode(item.id,item.title)"><qrcode-outlined/> 二维码</span>
            <a-dropdown placement="bottomRight">
              <span class="action">更多 <down-outlined class="font-size-smaller"/></span>
              <template #overlay>
                <a-menu>
                  <a-menu-item key="1">
                    <router-link :to="'/admin/coffee/editor/'+item.id">
                      <form-outlined/> 编辑
                    </router-link>
                  </a-menu-item>
                  <a-menu-item key="recommend" @click="handleChangeRecommend(item.id)"><like-outlined/> 推荐</a-menu-item>
                  <a-menu-item key="2" @click="handleChangeStatus(item.id)">
                    <span v-if="!item.status"><check-circle-outlined/> 启用</span>
                    <span v-else><close-circle-outlined/> 关闭</span>
                  </a-menu-item>
                  <a-menu-divider/>
                  <a-menu-item key="3" @click="handleDelete(item)"><delete-outlined/> 删除</a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </template>
        </a-list-item>
      </template>
     </a-list>
     <use-pagination :total="state.total" v-model:page="state.page" @change="pageChange"/>
    </a-card>
    <a-modal title="咖啡二维码" v-model:open="state.modal" :footer="false" :width="360">
      <a-flex justify="center" class="margin-bottom-md">
        <a-qrcode ref="qrcodeRef" :value="state.qrcode_url" id="qrcode" type="svg" :size="240" :bordered="false"/>
      </a-flex>
      <div class="modal-coffee-title">{{ state.coffee_title }}</div>
      <a-button block type="dashed" @click="downloadQrcode"><download-outlined/>下载二维码</a-button>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
import {UsePageHeader, UsePagination} from '@/components/';
import { FilterCoffee } from './components';
import {
  PlusOutlined,
  EyeOutlined,
  HeartOutlined,
  ClockCircleOutlined,
  FileSearchOutlined,
  QrcodeOutlined,
  DownOutlined,
  FormOutlined,
  DeleteOutlined,
  CloseCircleOutlined,
  CheckCircleOutlined,
  DownloadOutlined,
  LikeOutlined,
  UserOutlined} from '@ant-design/icons-vue';
import { onMounted, reactive, ref } from 'vue';
import { changeCoffeeRecommend, changeCoffeeStatus, deleteCoffee, getCoffeeList } from '@/server/modules/coffee';
import useMessage from '@/hooks/useMessage';
import { baseURL, staticURL } from '@/config';
import { hasPermission } from '@/hooks';
import { Modal } from 'ant-design-vue';

//列表数据
const data = ref<Coffee[]>([])
// 二维码弹窗ref对象 
const qrcodeRef = ref()
/**
 * 页面状态
 */
const state = reactive({
  total: 0,
  page: 1,
  page_size: 10,
  loading:false,
  modal:false,
  coffee_title:'',
  qrcode_url:'',
  coffee_id:0,
  keywords:'',
  category:0,
  sort:'-id',
  user_id:0
})
const onChange = (e: FilterParams)=> {
  //绑定筛选参数
  state.category = e.category
  state.user_id = e.user_id
  state.sort = e.sort
  state.keywords = e.keywords
  // 刷新数据
  getData()
}
/**
 * 获取数据
 */
const getData = async ()=> {
  try {
    state.loading = true
    const params = {
      page:state.page,
      page_size:state.page_size,
      keywords:state.keywords,
      sort:state.sort,
      user_id:state.user_id,
      category:state.category
    }
    const res = await getCoffeeList(params)
    if(res.code === 200){
      state.total = res.data.total
      data.value = res.data.data
      state.page = res.data.page
      state.page_size = res.data.page_size
    }else{
      useMessage(res.code,res.message)
    }
  } catch (error) {
    useMessage(500,'数据请求错误'+error)
  } finally { 
    setTimeout(() => {
      state.loading = false
    }, 500);
  }
}
/**
 * 挂载前请求数据
 */
onMounted(()=> {
  getData()
})
/**
 * 监听翻页参数
 * @param page 翻页参数
 */
const pageChange = (page:{page:number,page_size:number})=> {
  state.page = page.page
  state.page_size = page.page_size
  setTimeout(() => {
    getData()
  }, 100);
}
/**
 * 展示二维码
 * @param id 咖啡id
 * @param title 咖啡标题
 */
const showQrcode = (id:number,title:string) => {
  state.qrcode_url = baseURL+'coffee/'+id
  state.coffee_title = title
  state.modal = true
  state.coffee_id = id
}
/**
 * 下载SVG格式二维码，利于后期设置制作
 * 设置尺寸为1024*1024
 */
const downloadQrcode = async() => { 
  const d = document.getElementById('qrcode')
  //获取元素内的svg
  const svg = d?.querySelector('svg')
  if(svg){
    svg?.setAttribute('width', '1024')
    svg?.setAttribute('height', '1024')
    svg?.setAttribute('xmlns', 'http://www.w3.org/2000/svg')
    const svgData = new XMLSerializer().serializeToString(svg)
    const blob = new Blob([svgData], {type: 'image/svg+xml;charset=utf-8'})
    // 创建下载链接
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `coffee-${state.coffee_id}.svg`;
    
    // 执行下载
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  }
}
/**
 * 修改显示状态
 * @param id 
 */
const handleChangeStatus = async (id:number) => { 
  if(!hasPermission('update')) return
  const res = await changeCoffeeStatus(id)
  if(res.code === 200){
    getData()
  }
  useMessage(res.code,res.message)
}
/**
 * 推荐推荐状态
 * @param id 
 */
const handleChangeRecommend = async (id:number) => {
  if(!hasPermission('update')) return 
  const res = await changeCoffeeRecommend(id)
  if(res.code === 200){
    getData()
  }
  useMessage(res.code,res.message)
}
/**
 * 删除
 * @param item 
 */
const handleDelete = async (item:Coffee) => { 
  if(!hasPermission('delete')) return
  Modal.confirm({
    title:'删除确认',
    content:`您将删除文章 ${item.title} ，请谨慎删除，此操作不可逆！`,
    onOk:async()=>{
      const res = await deleteCoffee(item.id)
      if(res.code === 200){
        getData()
      }
      useMessage(res.code,res.message)
    }
  })
}
</script>
<style scoped>
.modal-coffee-title{
  background-color: #f5f5f5;
  padding: 8px;
  border-radius: 6px;
  margin-bottom: 12px;
}
.category {
  background-color: #f5f5f5;
  padding: 0 8px;
  border-radius: 4px;
}
</style>